const yh = document.getElementById("yh");
const mm = document.getElementById("mm");
const remm = document.getElementById("remm");
const yzm = document.getElementById("yzm");
const hqyzm = document.getElementById("hqyzm");

// 验证码倒计时
let flag = true
hqyzm.addEventListener("click", function () {
  if (flag) {
    flag = false
    let i = 9
    hqyzm.innerHTML = `0${i}秒后重新发送`
    let ti = setInterval(function () {
      i--;
      hqyzm.innerHTML = `0${i}秒后重新发送`
      if (i == 0) {
        hqyzm.innerHTML = `发送验证码`
        clearInterval(ti)
        flag = true
      }
    }, 1000)
  }
})

//用户名正则表达式
const m1 = document.querySelector('#m1')
yh.addEventListener("change", yhhs)
function yhhs() {
  const reg = /^\w{6,20}$/
  if (!reg.test(yh.value)) {
    m1.innerHTML = '请输入6-20位字母数字下划线'
    return false
  } else {
    m1.innerHTML = ''
    return true
  }
}

//密码正则表达式
const m2 = document.querySelector('#m2')
mm.addEventListener("change", mmhs)
function mmhs() {
  const reg = /^\w{6,20}$/
  if (!reg.test(mm.value)) {
    m2.innerHTML = '请输入6-20位字母数字下划线'
    return false
  } else {
    m2.innerHTML = ''
    return true
  }
}

//确认密码
const m3 = document.querySelector('#m3')
remm.addEventListener("change", remmhs)
function remmhs() {
  if (remm.value !== mm.value) {
    m3.innerHTML = '两次密码不一致'
    return false
  } else {
    m3.innerHTML = ''
    return true
  }
}

//验证码
const m4 = document.querySelector('#m4')
yzm.addEventListener("change", yzmhs)
function yzmhs() {
  const yzms = '1234'
  if (yzm.value !== yzms) {
    m4.innerHTML = '请输入正确验证码'
    return false
  } else {
    m4.innerHTML = ''
    return true
  }
}

//勾选协议
const checkbox = document.getElementById("agreement");
const form = document.querySelector("form");
form.addEventListener("submit", e => {
  e.preventDefault();
  if (!checkbox.checked) {
    alert("请勾选协议");
  }
  if (!yhhs()) return
  if (!mmhs()) return
  if (!remmhs()) return
  if (!yzmhs()) return

  axios({
    url: "/register",
    method: "post",
    data: {
      username: yh.value,
      password: mm.value
    }
  }).then(res => {
    if (res.code == 1) {
      console.log(res.msg);
      myAlert(false, res.msg)
    } else {
      console.log(res.msg);
      myAlert(true, res.msg)
      setTimeout(() => {
        location.href = "../login/index.html"
      }, 1000)
    }
  })
})
